#
# Copyright (C) Since 2018 ~ 2025, Inc. All Rights Reserved
#
# @Time    : 2025/1/14-下午8:00
# @Author  : Timmy
# @Email   : tangping@cloudstream-tech.com
# @File    : frontend.py
# @Software: lottery
# @Function:
#


import asyncio
import os

import tornado
from tornado.web import RequestHandler
from tornado.websocket import WebSocketHandler

static_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "static")


class WSHandler(WebSocketHandler):
    _frontend = []
    _terminal = []
    _client = {}

    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self._client_id = None

    def open(self, client_id):
        self._client_id = client_id
        match client_id:
            case "frontend":
                self._frontend.append(self)
            case "terminal":
                self._terminal.append(self)
            case _:
                self._client[client_id] = self

        print("WebSocket opened:", client_id)

    def on_message(self, message):
        match self._client_id:
            case "frontend":
                for terminal in self._terminal:
                    terminal.write_message(message)
            case "terminal":
                for frontend in self._frontend:
                    frontend.write_message(message)
            case _:
                for _id, client in self._client.items():
                    if _id == self._client_id:
                        continue
                    client.write_message(message)
                self.write_message("You said: " + message)
        # print("Received message:", message)

    def on_close(self):
        match self._client_id:
            case "frontend":
                self._frontend.remove(self)
            case "terminal":
                self._terminal.remove(self)
            case _:
                self._client.pop(self._client_id)
        print("WebSocket closed")

    def check_origin(self, origin):
        return True  # For cross-origin requests


class MainHandler(RequestHandler):
    def get(self):
        self.write("Hello, world")


def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
        (r"/static/(.*)", tornado.web.StaticFileHandler, {"path": static_path}),
        (r"/ws/(.*)", WSHandler),
    ], static_path=static_path)


shutdown = asyncio.Event()


async def web_server():
    app = make_app()
    app.listen(8000)

    try:
        await shutdown.wait()
        print("Shutting down...")
    except (asyncio.CancelledError, KeyboardInterrupt) as e:
        print(e)


def stop_server():
    shutdown.set()


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(web_server())


